package com.itheima.health.security.config;

import com.itheima.health.security.security.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfig2 extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //指定访问控制规则
        //1-通过authorizeRequests()开启一个拦截规则
        //2_通过antMatchers指定需要拦截的资源,参数为ant表达式

        //允许所有访问
        http.authorizeRequests().antMatchers("*.js", "*.css").access("permitAll()");
        //允许拥有"add"权限和"ROLE_ADMIN"角色的人访问
        http.authorizeRequests().antMatchers("/pages/checkitem.html").access("hasAnyAuthority('add','ROLE_ADMIN')");
        //允许拥有"find"权限访问
        http.authorizeRequests().antMatchers("/pages/checkgroup.html").access("hasAuthority('find')");
        //允许登陆的人访问
        http.authorizeRequests().antMatchers("/main.html", "/pages/**").access("isAuthenticated()");
        //使用springSecurity默认的登陆配置
        //http.formLogin();

        //配置登录表单相关内容
        http.formLogin().loginPage("/login.html")
                .loginProcessingUrl("/sec/login")
                .failureUrl("/login-fail.html")
                .defaultSuccessUrl("/main.html");

        //关闭csrf
        http.csrf().disable();

        http.logout().logoutUrl("/sec/logout")
                .logoutSuccessUrl("/login.html")
                .invalidateHttpSession(true);
        http.exceptionHandling().accessDeniedPage("/auth-fail.html");

    }
}
